<template>
  <PageWrapper dense contentFullHeight contentClass="flex">
    <DeptTree class="w-1/4 xl:w-1/5 m-4 mr-0" @select="handleSelect" />
    <BasicTable
      @register="registerTable"
      class="w-3/4 xl:w-4/5"
      @selection-change="selectionChange"
      :searchInfo="searchInfo"
    >
      <template #toolbar>
        <a-button v-if="hasPermission('user:save')" type="primary" @click="handleCreate">
          新增用户
        </a-button>
        <a-button
          v-if="hasPermission('user:delete')"
          type="primary"
          :disabled="wacthEdit()"
          @click="handleDelete"
          danger
        >
          批量删除
        </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'account'">
          <Tooltip>
            <template #title> 当前登录的账号 </template>
            <Radio v-if="(userStore.userInfo || {}).userId === record.id" checked />
          </Tooltip>
          {{ record.account }}
        </template>
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'clarity:note-edit-line',
                onClick: handleEdit.bind(null, record),
                auth: 'user:update',
              },
              {
                icon: 'ant-design:delete-outlined',
                color: 'error',
                auth: 'user:delete',
                popConfirm: {
                  title: '是否确认删除',
                  placement: 'left',
                  confirm: handleDelete.bind(null, record),
                },
                ifShow: (_action) => {
                  return record.userType !== USER_TYPE.ADMIN;
                },
              },
              {
                icon: 'clarity:key-line',
                auth: 'user:reset:pass',
                onClick: handleResetPwd.bind(null, record),
                ifShow: (_action) => {
                  return record.userType !== USER_TYPE.ADMIN;
                },
              },
              {
                auth: 'user:auth:role',
                icon: 'clarity:attachment-line',
                onClick: handleAuthRole.bind(null, record),
                ifShow: (_action) => {
                  return record.userType !== USER_TYPE.ADMIN;
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <SysUserModal @register="registerModal" @success="handleSuccess" />
    <editPass @register="editModal" @success="handleSuccess" />
    <userTransfer @register="transferModel" @success="handleSuccess" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { h, reactive } from 'vue';
  import { message, Radio, Tooltip } from 'ant-design-vue';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { useModal } from '@/components/Modal';
  import SysUserModal from './sys-user-modal.vue';
  import userTransfer from './user-transfer.vue';
  import editPass from './edit-pass.vue';
  import DeptTree from './dept-tree.vue';
  import { PageWrapper } from '@/components/Page';
  import { getUserPageApi, delUserApi } from '@/api/system/user';
  import { columns, searchFormSchema } from './data';
  import { usePermission } from '@/hooks/web/usePermission';
  import { useMessage } from '@/hooks/web/useMessage';
  import { SystemUserItem, USER_TYPE } from '@/api/system/model/userModel';
  import { useUserStore } from '@/store/modules/user';

  const userStore = useUserStore();

  const { hasPermission } = usePermission();
  const { createConfirm } = useMessage();
  const [registerTable, { reload, getSelectRows }] = useTable({
    title: '用户管理',
    api: getUserPageApi,
    columns,
    rowKey: 'id',
    formConfig: {
      schemas: searchFormSchema,
      labelWidth: 70,
    },
    rowSelection: {
      type: 'checkbox',
      getCheckboxProps: (record: SystemUserItem) => ({
        disabled: record.userType === USER_TYPE.ADMIN,
      }),
    },

    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    showIndexColumn: false,
    actionColumn: {
      width: 160,
      title: '操作',
      dataIndex: 'action',
      fixed: undefined,
    },
  });

  const searchInfo = reactive<Recordable>({});
  const [registerModal, { openModal }] = useModal();
  const [editModal, { openModal: openEditModel }] = useModal();
  const [transferModel, { openModal: openTransferModel }] = useModal();

  function wacthEdit() {
    const res = getSelectRows();
    if (res.length > 0) {
      return false;
    } else {
      return true;
    }
  }

  function handleCreate() {
    openModal(true, {});
  }

  function handleEdit(record: Recordable) {
    console.log(record);
    openModal(true, record);
  }

  async function handleDelete(record: Recordable) {
    // console.log(record.id);
    if (record.id) {
      await delUserApi(record.id);
      reload();
    } else {
      const delData = getSelectRows();
      if (delData.length === 0) {
        message.warning('请选择数据');
        return;
      }
      createConfirm({
        iconType: 'warning',
        title: () => h('span', '提示'),
        content: () => h('span', `确认删除${delData.map((item) => item.username).join('、')}吗？`),
        onOk: async () => {
          await delUserApi(delData.map((item) => item.id).join(','));
          reload();
        },
      });
    }
  }

  function handleResetPwd(record: Recordable) {
    console.log(record);
    openEditModel(true, record);
  }

  function handleAuthRole(record: Recordable) {
    console.log(record);
    openTransferModel(true, record);
  }

  function handleSelect(deptId = '') {
    console.log(deptId);
    searchInfo.deptId = deptId;
    reload();
  }

  function selectionChange({ keys, rows }) {
    console.log(keys, rows);
    // delWorkflowCategoryApi(record.categoryId);
  }
  function handleSuccess() {
    reload();
  }
</script>
